<?php
class IndexAction extends CommonAction {

    //初始化
    protected function _initialize(){
        $this->redis_cache_connect();
    }

    //价格区间
    private $priceItem = array(
        '1'=>array(
            'min' => 0,
            'max' => 3000,
            'name' => '0~3千'
        ),
        '2'=>array(
            'min' => 3000,
            'max' => 6000,
            'name' => '3千~6千'
        ),
        '3'=>array(
            'min' => 6000,
            'max' => 10000,
            'name' => '6千~1万'
        ),
        '4'=>array(
            'min' => 10000,
            'max' => 15000,
            'name' => '1万-1.5万'
        ),
        '5'=>array(
            'min' => 15000,
            'max' => 20000,
            'name' => '1.5万-2万'
        ),
        '6'=>array(
            'min' => 20000,
            'max' => 30000,
            'name' => '2万-3万'
        ),
        '7'=>array(
            'min' => 30000,
            'max' => 0,
            'name' => '3万以上'
        ),
    );
    //申请人注册量
    private $applyCountItem = array(
        '1'=>array(
            'min' => 1,
            'max' => 50,
            'name' => '1-50'
        ),
        '2'=>array(
            'min' => 1,
            'max' => 100,
            'name' => '1-100'
        ),
        '3'=>array(
            'min' => 1,
            'max' => 150,
            'name' => '1-150'
        ),
        '4'=>array(
            'min' => 151,
            'max' => 200,
            'name' => '151-200'
        ),
        '5'=>array(
            'min' => 200,
            'max' => 0,
            'name' => '200以上'
        ),
    );
    //组合类型
    private $combinedTypeItem = array(
        '1'=>array(
            'name' => '纯中文'
        ),
        '2'=>array(
            'name' => '纯数字'
        ),
        '3'=>array(
            'name' => '纯图形'
        ),
        '4'=>array(
            'name' => '纯英文'
        ),
        '5'=>array(
            'name' => '中文+英文'
        ),
        '6'=>array(
            'name' => '中文+数字'
        ),
        '7'=>array(
            'name' => '英文+数字'
        ),
    );
    //商标字数
    private $stringCountItem = array(
        '1'=>array(
            'name' => '1个字'
        ),
        '2'=>array(
            'name' => '2个字'
        ),
        '3'=>array(
            'name' => '3个字'
        ),
        '4'=>array(
            'name' => '4个字'
        ),
        '5'=>array(
            'name' => '5个字'
        ),
        '6'=>array(
            'name' => '6个字'
        ),
        '7'=>array(
            'name' => '7个字及以上'
        ),
    );
    //申请人类型
    private $applyerTypeItem = array(
        '1'=>array(
            'name' => '仅公司'
        ),
        '2'=>array(
            'name' => '仅个人'
        ),
    );
    //注册年限类型
    private $registedYearsItem = array(
        '1'=>array(
            'name' => '1年以内'
        ),
        '2'=>array(
            'name' => '1-2年'
        ),
        '3'=>array(
            'name' => '2-3年'
        ),
        '4'=>array(
            'name' => '3年以上'
        ),
    );
    //商标名称结构类型
    private $structTypeItem = array(
        '1'=>array( 'name' => 'AA' ),
        '2'=>array( 'name' => 'AB' ),
        '3'=>array( 'name' => 'ABB' ),
        '4'=>array( 'name' => 'AAB' ),
        '5'=>array( 'name' => 'AAA' ),
        '6'=>array( 'name' => 'AAAA' ),
        '7'=>array( 'name' => 'AABB' ),
        '8'=>array( 'name' => 'ABAB' ),
        '9'=>array( 'name' => 'ABBB' ),
        '10'=>array( 'name' => 'AAAB' ),
        '11'=>array( 'name' => 'ABAC' ),
        '12'=>array( 'name' => 'AABC' ),
        '13'=>array( 'name' => 'ABCC' ),
    );

    public function index(){
        $search = htmlspecialchars(trim($this->_get('c')));
        $slefMinPrice = htmlspecialchars(trim($this->_get('min')));
        $slefMaxPrice = htmlspecialchars(trim($this->_get('max')));
        $keywords = htmlspecialchars(trim($this->_get('k')));
        $st = intval(htmlspecialchars(trim($this->_get('st'))));
        $sm = intval(htmlspecialchars(trim($this->_get('sm'))));
        $orderBy = $this->_get("order","intval",0); //排序
        $groupBy = $this->_get("group","intval",0); //分组
        $searchArr = explode('-',$search);
        $s = array(
            "priceId" => isset($searchArr[0]) ? intval($searchArr[0]) : 0,
            "cateId" => isset($searchArr[1]) ? intval($searchArr[1]) : 0,
            "groupId" => ( intval($searchArr[2]) > 0 ) ? $searchArr[2] : 0,
            "applyCountId" => isset($searchArr[3]) ? intval($searchArr[3]) : 0,
            "combinedTypeId" => isset($searchArr[4]) ? intval($searchArr[4]) : 0,
            "stringCountId" => isset($searchArr[5]) ? intval($searchArr[5]) : 0,
            "applyerTypeId" => isset($searchArr[6]) ? intval($searchArr[6]) : 0,
            "registedYearsId" => isset($searchArr[7]) ? intval($searchArr[7]) : 0,
            "structTypeId" => isset($searchArr[8]) ? intval($searchArr[8]) : 0,
        );
        if( $s['cateId'] >= 0 ){
            //查询分类下的群组W
            $groupItem = $this->getGroup($s['cateId']);
            if( !empty($groupItem) ){
                $this->assign('group',$groupItem);
            }
        }
        //查询商标
        $where = array();
        //$where['status'] = 1;
        $where[] = "m.status = 1";
        $params = $otherparams = '';
        //自定义价格
        if( !empty($slefMinPrice) || !empty($slefMaxPrice) ){
            $slefMinPrice = intval($slefMinPrice);
            $slefMaxPrice = intval($slefMaxPrice);
            if( $slefMinPrice == 0 && $slefMaxPrice > 0 ){
                //$where['m.trademark_price'] = array('elt', $slefMaxPrice);
                $where[] = "m.trademark_price <= {$slefMaxPrice}";
            }elseif( $slefMinPrice > 0 && $slefMaxPrice == 0 ){
                //$where['m.trademark_price'] = array('egt', $slefMinPrice);
                $where[] = "m.trademark_price >= {$slefMinPrice}";
            }elseif( $slefMinPrice > 0 && $slefMaxPrice > 0 ){
                //$where['m.trademark_price'] = array('between', array($slefMinPrice,$slefMaxPrice));
                $where[] = "m.trademark_price BETWEEN {$slefMinPrice} AND {$slefMaxPrice}";
            }
            //重置价格选项
            $s['priceId'] = 0;
        }
        //价格
        if( $s['priceId'] > 0 ){
            if(isset($this->priceItem[$s['priceId']])){
                $priceItemInfo = $this->priceItem[$s['priceId']];
                $minPrice = $priceItemInfo['min'];
                $maxPrice = $priceItemInfo['max'];
                //$where['m.trademark_price'] = array('between', array($minPrice,$maxPrice));
                $where[] = "m.trademark_price BETWEEN {$minPrice} AND {$maxPrice}";
            }
        }
        //商标分类
        if( $s['cateId'] > 0 ){
            //$where['m.trademark_cate'] = $s['cateId'];
            $where[] = "m.trademark_cate = {$s['cateId']}";
        }
        //商标名称长度
        if( $s['stringCountId'] > 0 ){
            if(isset($this->stringCountItem[$s['stringCountId']])){
                //$where['m.trademark_name_length'] = $s['stringCountId'];
                $where[] = "m.trademark_name_length = {$s['stringCountId']}";
            }
        }
        //商标名称组合类型
        if( $s['combinedTypeId'] > 0 ){
            if(isset($this->combinedTypeItem[$s['combinedTypeId']])){
                //$where['m.trademark_name_combined_type'] = $s['combinedTypeId'];
                $where[] = "m.trademark_name_combined_type = {$s['combinedTypeId']}";
            }
        }
        //商标年限
        if( $s['registedYearsId'] > 0 ){
            if(isset($this->registedYearsItem[$s['registedYearsId']])){
                if( $s['registedYearsId'] == 1 ){
                    $afterOneYear = date("Y-m-d H:i:s",strtotime("-1 year", time()));
                    //$where['m.trademark_apply_time'] = array("egt",$afterOneYear);
                    $where[] = "m.trademark_apply_time >= '{$afterOneYear}'";
                }
                if( $s['registedYearsId'] == 2 ){
                    $afterOneYear = date("Y-m-d H:i:s",strtotime("-1 year", time()));
                    $afterTwoYear = date("Y-m-d H:i:s",strtotime("-2 year", time()));
                    //$where['m.trademark_apply_time'] = array('between', array($afterOneYear,$afterTwoYear));
                    $where[] = "m.trademark_apply_time BETWEEN '{$afterTwoYear}' AND '{$afterOneYear}'";
                }
                if( $s['registedYearsId'] == 3 ){
                    $afterTwoYear = date("Y-m-d H:i:s",strtotime("-2 year", time()));
                    $afterThreeYear = date("Y-m-d H:i:s",strtotime("-3 year", time()));
                    //$where['m.trademark_apply_time'] = array('between', array($afterTwoYear,$afterThreeYear));
                    $where[] = "m.trademark_apply_time BETWEEN '{$afterThreeYear}' AND '{$afterTwoYear}'";
                }
                if( $s['registedYearsId'] == 4 ){
                    $afterThreeYear = date("Y-m-d H:i:s",strtotime("-3 year", time()));
                    //$where['m.trademark_apply_time'] = array('elt', $afterThreeYear);
                    $where[] = "m.trademark_apply_time <= '{$afterThreeYear}'";
                }
            }
        }
        //商标名称结构类型
        if( $s['structTypeId'] > 0 ){
            if(isset($this->structTypeItem[$s['structTypeId']])){
                //$where['m.trademark_name_struct_type'] = $s['structTypeId'];
                $where[] = "m.trademark_name_struct_type = '{$s['structTypeId']}'";
            }
        }

        if($search){
            $params .= '/c/' . $search;
        }
        if( $slefMinPrice ){
            $params .= '/min/' . $slefMinPrice;
            $otherparams .= '/min/' . $slefMinPrice;
        }
        if( $slefMaxPrice ){
            $params .= '/max/' . $slefMaxPrice;
            $otherparams .= '/max/' . $slefMaxPrice;
        }
        if( $st ){
            $params .= '/st/' . $st;
            $otherparams .= '/st/' . $st;
        }
        if( $sm ){
            $params .= '/sm/' . $sm;
            $otherparams .= '/sm/' . $sm;
        }
        $whereKeywordsStr = "";
        if( $keywords ){
            $params .= '/k/' . $keywords;
            $otherparams .= '/k/' . $keywords;
            $whereKeywordsStr = " AND ( " . $this->getWhereSearchKeywordStr($sm, $st ,$keywords) . " )";
        }
        
        $ordergroupparams = "";
        //排序
        $orderStr = "m.id ASC";
        if($orderBy){
            $ordergroupparams = "order={$orderBy}&";
            if($orderBy == 1){
                $orderStr = "m.id DESC";
            }else if($orderBy == 2){
                $orderStr = "m.trademark_price ASC";
            }else if($orderBy == 3){
                $orderStr = "m.trademark_price DESC";
            }
        }
        //分组
        $groupStr = "";
        if($groupBy){
            $ordergroupparams .= "group={$groupBy}";
            $groupStr = "m.trademark_sn";
        }
        if($ordergroupparams){
            $ordergroupparams = "?" . rtrim($ordergroupparams,"&");
            $otherparams .= $ordergroupparams;
        }
        //分类
        $trademarksCategory = $this->getCategory();
    
        $this->M->page['no'] = $this->_get('p') ? $this->_get('p', 'intval') : 1;
        $this->M->page['num'] = 25;

        $whereStr = implode(" AND ", $where) . $whereKeywordsStr;
        if(empty($groupStr)){
            $this->M->page['total'] = ceil(M('trademarks m')->where($whereStr)->count() / $this->M->page['num']);
            $trademarks = M('trademarks m')->where($whereStr)->field('m.*')->limit($this->page_limit())->order($orderStr)->select();
        }else{
            $groupCountSql = "SELECT COUNT(tab.t) AS tp_count FROM (SELECT count(m.id) t FROM trademarks m WHERE {$whereStr} GROUP BY {$groupStr} ORDER BY {$orderStr}) AS tab";
            $countResult = M()->query($groupCountSql);
            $this->M->page['total'] = ceil($countResult[0]['tp_count'] / $this->M->page['num']);
            $trademarks = M('trademarks m')->where($whereStr)->field('m.*')->limit($this->page_limit())->group($groupStr)->order($orderStr)->select();
        }
        foreach ( $trademarks as $k => $v ) {
            $trademarks[$k]['cate_info'] = $trademarksCategory[$v['trademark_cate']];
        }

        $pageurl = '/index/index' . $params . '/p/*.html' . $ordergroupparams;
        $this->set_pages($pageurl);

        $this->assign('priceId',$s['priceId']);
        $this->assign('cateId',$s['cateId']);
        $this->assign('groupId',$s['groupId']);
        $this->assign('applyCountId',$s['applyCountId']);
        $this->assign('applyerTypeId',$s['applyerTypeId']);
        $this->assign('stringCountId',$s['stringCountId']);
        $this->assign('combinedTypeId',$s['combinedTypeId']);
        $this->assign('registedYearsId',$s['registedYearsId']);
        $this->assign("structTypeId",$s['structTypeId']);
        $this->assign('priceItem',$this->priceItem);
        $this->assign('applyCountItem', $this->applyCountItem);
        $this->assign('stringCountItem', $this->stringCountItem);
        $this->assign('applyerTypeItem', $this->applyerTypeItem);
        $this->assign('combinedTypeItem', $this->combinedTypeItem);
        $this->assign('registedYearsItem', $this->registedYearsItem);
        $this->assign('structTypeItem', $this->structTypeItem);
        $this->assign('category', $trademarksCategory);
        $this->assign('trademarks', $trademarks);
        $this->assign("c",empty($search) ? 0 : 1);
        $this->assign("otherparams",$otherparams);
        $this->assign('minprice', $slefMinPrice);
        $this->assign('maxprice', $slefMaxPrice);
        $this->assign('st', ( $st >= 0 ) ? $st : 0);
        $this->assign('sm', ( $sm >= 0 ) ? $sm : 0);
        $this->assign('keywords', $keywords);
        $this->display('Index:index');
    }

    private function getCategory(){
        /*
        $cate_id = 11;
        $int_group_sn = 1100;
        $length = 13;
        $jump = array('1102');
        for($i = 1; $i<= $length; $i++){
            if( $int_group_sn < 1000 ){
                $group_sn = str_pad(($int_group_sn + $i),4,'0',STR_PAD_LEFT);
            }else{
                $group_sn = $int_group_sn + $i;
            }
            if( !in_array($group_sn,$jump) ){
                $insertData = array();
                $insertData['cate_id'] = $cate_id;
                $insertData['group_sn'] = $group_sn;
                $trademarksGroup = M("trademarks_group")->where(array('cate_id'=>$cate_id,'group_sn' => $group_sn))->find();
                if( !$trademarksGroup  ){
                    M("trademarks_group")->add($insertData);
                }
            }
        }
        */
        $key = "index_index_trademarks_category";
        $jsonData = $this->redis_cache->get($key);
        $list = json_decode($jsonData,true);
        if(empty($list)){
            $list = M("trademarks_category")->select();
            $this->redis_cache->setex($key, 60 * 60, json_encode($list));
        }
        return $list;
    }

    /**
     * 查询商标分类下的群组列表
     * @param $cateId
     * @return false|mixed|string|null
     */
    private function getGroup($cateId){
        $list = [];
        if($cateId > 0){
            $key = "index_index_trademarks_group_cateId_{$cateId}";
            $jsonData = $this->redis_cache->get($key);
            $list = json_decode($jsonData, true);
            if(empty($list)){
                $result = M("trademarks_group")->where(array('cate_id'=>$cateId))->order('group_sn ASC')->select();
                foreach ($result as $item){
                    $list[ $item['id'] ] = $item;
                }
                $this->redis_cache->setex($key , 60 * 60, json_encode($list));
            }
        }
        return $list;
    }

    /**
     * 获取搜索关键词WHERE条件
     *
     * @param [type] $sm
     * @param [type] $st
     * @param [type] $keywords
     * @return string
     */
    private function getWhereSearchKeywordStr($sm, $st, $keywords){
        $where = [];
        if( $sm == 0 || $sm == 3 ){
            if( $st == 1 ){
                //$where['m.trademark_name'] = array("like",$keywords . '%');
                $where[] = "m.trademark_name like '%{$keywords}%'";
            }elseif( $st == 2  ){
                //$where['m.trademark_sn'] = array("like",$keywords . '%');
                $where[] = "m.trademark_sn like '%{$keywords}%'";
            }elseif( $st == 3  ){
                //申请人
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}%'";
            }elseif( $st == 0  ){
                //智能
                $where[] = "m.trademark_name like '%{$keywords}%'";
                $where[] = "m.trademark_sn like '%{$keywords}%'";
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}%'";
            }
        }elseif( $sm == 1 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name like '{$keywords}%'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn like '{$keywords}%'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name like '{$keywords}%'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name like '{$keywords}%'";
                $where[] = "m.trademark_sn like '{$keywords}%'";
                $where[] = "m.trademark_register_chinese_name like '{$keywords}%'";
            }
        }elseif( $sm == 2 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name like '%{$keywords}'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn like '%{$keywords}'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name like '%{$keywords}'";
                $where[] = "m.trademark_sn like '%{$keywords}'";
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}'";
            }
        }elseif( $sm == 4 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name = '{$keywords}'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn = '{$keywords}'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name = '{$keywords}'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name = '{$keywords}'";
                $where[] = "m.trademark_sn = '{$keywords}'";
                $where[] = "m.trademark_register_chinese_name = '{$keywords}'";
            }
        }
        return implode(" OR ",$where);
    }
}